package com.example;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.datasource.AbstractDataSource;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.zookeeper.ZookeeperDataSource;
import com.alibaba.csp.sentinel.property.SentinelProperty;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@SpringBootApplication
public class SentinelRestApplication implements CommandLineRunner {

	public static void main(String[] args) {
		SpringApplication.run(SentinelRestApplication.class, args);
	}

	@Override
	public void run(String... strings) throws Exception {
//		List<FlowRule> rules = new ArrayList<>();
//		FlowRule rule = new FlowRule();
//		rule.setResource("/rest/helloWorld");
//		rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
//		// Set limit QPS to 20.
//		rule.setCount(2);
//		rules.add(rule);
//		FlowRuleManager.loadRules(rules);

		final String remoteAddress = "127.0.0.1:2181";
		final String path = "/sentinel-rest/rule";

		ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new ZookeeperDataSource<>
				(remoteAddress, path, source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {}));
		FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
	}

	@RequestMapping("helloWorld")
	public void helloWorld() {
		System.out.println("hello world");
	}

	@RequestMapping("helloWorld2")
	public void helloWorld2() {
		System.out.println("hello world2");
	}

}
